<?php
class Contributors extends MY_Controller 
{
	var $curl = 'contributors';
	var $name = '';
	var $search = '';
	var $per_page = 0;
	var $language;
	var $submenu = "_menu";
	var $id_user = '';
	
	function __construct()
	{
		parent::__construct();
		
		$this->load->model(array('/public/contributor_model', '/public/account_type_model', '/public/geo_state_model', '/public/geo_city_model'));

		$this->validation->set_fields($this->contributor_model->fields);
		
		$this->data['Title'] = T_('Contributors');		

		$this->language = parent::getLang();

		$this->name = T_('Contributors');
	}
	
	function index()
	{
		$this->contributor_model->search();
		
		$this->renderLayout();
	}

	function search_autocomplete()
	{
		echo $this->contributor_model->search_autocomplete();
	}
	
	function create()
	{
		if (!empty($_POST))
		{
			$rules = array('first_name', 'last_name', 'phone', 'id_account_type', 'email', 'password',  'password_confirm', 'status', 'hear_type');
			$this->validation->set_rules($this->contributor_model->getRules($rules));
					
			$this->validation->set_message('__loginFree', '<span class="black bold">«'.T_("User").'»</span> '.T_("already exists with such email. Please change the email."));								
			
			if ($this->validation->run() === TRUE)
			{				
				$item['first_name'] 	= $this->validation->first_name;
				$item['last_name']		= $this->validation->last_name;
				$item['phone'] 			= $this->validation->phone;
				$item['id_account_type']= $this->validation->id_account_type;
				$item['email'] 			= $this->validation->email;
				$item['password'] 		= $this->validation->password;	
				$item['hear_type'] 		= $this->validation->hear_type;				
				$item['status'] 		= $this->validation->status;
				
       			if ($id_user = $this->contributor_model->insert($item))
       			{	
					// Save User Roles
					$this->db->insert('users_roles', array('id_users' => $id_user, 'id_roles' => ROLE_CONTRIBUTOR, 'id_group' => CONTRIBUTOR_GROUP_ID));
					
         			redirect($this->curl . '/index'); 
       			}				
			}
		}
		else
		{
			//$this->validation->phone = 'some';
		}
		
		$this->data['Title'] .= ' / ' . T_('New Contributor');
		
		$this->renderLayout();			
	}
	
	function edit($id = null)
	{
		if (!empty($id))
		{
			$object = $this->contributor_model->get($id);
			
			if (!count($object))
			{
				$this->renderElement('query_no_object');
				return false; 
			}
                			
			if (!count($_POST))
			{
				$this->validation->id 			= $object['id'];
				$this->validation->first_name 	= $object['first_name'];
				$this->validation->last_name 	= $object['last_name']; 
				$this->validation->phone 		= $object['phone'];
				$this->validation->id_account_type = $object['id_account_type']; 
				$this->validation->email 		= $object['email'];
				$this->validation->hear_type 	= $object['hear_type'];
				$this->validation->status 		= $object['status'];
				$this->validation->balance		= $object['balance'];
				$this->validation->password 	= '';
				$this->validation->password_confirm = '';
			}
			else
			{				
				$this->id_user = $id;
				
				$rules = array('first_name', 'last_name', 'phone', 'id_account_type', 'email', 'new_password',  'password_confirm', 'status', 'hear_type');
				$this->validation->set_rules($this->contributor_model->getRules($rules));
								
				$this->validation->set_message('__loginFree', '<span class="black bold">«'.T_("User").'»</span> '.T_("already exists with such email. Please change the email."));
				
				if ($this->validation->run() === TRUE)
				{          						
					$item = array();
				 	$item['id'] 			= $this->validation->id;
				 	$item['first_name'] 	= $this->validation->first_name;
					$item['last_name']		= $this->validation->last_name;
					$item['phone'] 			= $this->validation->phone;
					$item['id_account_type']= $this->validation->id_account_type;
					$item['email'] 			= $this->validation->email;
					$item['hear_type'] 		= $this->validation->hear_type;				
					$item['status'] 		= $this->validation->status;
			        //$item['balance']    	= $this->validation->balance;
					
					if (!empty($this->validation->password))
					{
						$item['password'] 	= $this->validation->password;
					}
					
			       /*
					$day 	= $this->input->post('day');
					$month 	= $this->input->post('month');
					$year 	= $this->input->post('year');
					if ( !empty($day) && !empty($month) && !empty($year) )
					{
						$day = ($day < 10) ? '0' . $day : $day;
						$month = ($month < 10) ? '0' . $month : $month;
						$item['birth'] = $year . '-' . $month  . '-' . $day;   
					}*/
										
					$this->contributor_model->update($item);

					redirect($this->curl . '/index');
				}
			}	
		}
        	
		$this->data['Title'] .= ' / ' . T_('Edit');
		
		$this->renderLayout();
	}
	
	function account($id)
	{		
        $sql = "SELECT * 
                FROM stats.users_payments 
                WHERE id_users=".$this->db->escape($id)." 
                ORDER BY id DESC";
        $this->data['history'] = $this->db->query($sql)->result();
        		
		if (count($_POST))
		{			
			
			$rules = array('amount','notes');
			$this->validation->set_fields($this->accountcontributor_model->fields);
			$this->validation->set_rules($this->accountcontributor_model->getRules($rules));
			$this->validation->set_message('__positiveNumbers', '<span class="black bold">........');
						

			if ($this->validation->run() === TRUE)
			{			
								
				$item['id_users']		= $id;
				$item['dt']				= date('Y-m-d H:i:s');
				$item['type']			= 0;
				$item['notes']			= $this->validation->notes;	
				
				$item['amount'] = ($_POST['action'] == 'РћС‚РЅСЏС‚СЊ')
				?(-1*$this->validation->amount)
				:(1*$this->validation->amount);
					
						
				if ($this->accountcontributor_model->insert($item))
				{
					/*$sql = "SELECT nextval('advertisers_id_seq')";
					$sequence = $this->db->query($sql)->row();
					$id_advertiser = $sequence->nextval - 1;
					
					// Save User Roles					
					$this->db->insert('users_roles', array('id_users' => $id_advertiser, 'id_roles' => ROLE_COMPANY, 'id_group' => COMPANY_GROUP_ID));						
				*/	
					//Save User Bonus
			        /* $this->db->insert('stats.advertisers_payments', array('id_advertisers' => $id, 'dt' =>  date('Y-m-d H:i:s'), 'type' => 0, 
										'amount' => $var_amount, 'notes' => $this->validation->notes));
					*/
					redirect($this->curl . '/edit/'.$id);	
				}				
			}
		}
				
		$this->data['Title'] = 'РџРѕРїРѕР»РЅРёС‚СЊ СЃС‡РµС‚';
		$this->validation->id = $id;		
		
		$this->renderLayout();			
	}
	
	/*
	function targeting($id = null)
	{
		if (!empty($id))
		{
			$object = $this->contributor_model->get($id);
			
			if (!count($object))
			{
				$this->renderElement('query_no_object');
				return false; 
			}
			
			$this->data['user'] = (object)$object;			
			$this->data['all_categories'] = $this->category_model->getSelectOptions();
			
            $this->validation->campaign_categories = array();
            if (!empty($object['unwanted_categories']))
            {
                $var_array = explode(",", str_replace(array("{", "}"), "", $object['unwanted_categories']));
    
                foreach ($var_array as $value)
                {
                    $this->validation->campaign_categories[$value] = $this->data['all_categories'][$value];
                }
            }

            $this->data['categories'] = array_diff($this->data['all_categories'], $this->validation->campaign_categories);
				  	
			if (!count($_POST))
			{        
				$this->validation->id = $object['id'];
				$this->validation->with_sms   = ($object['with_sms'] == 't') ? 1 : 0;
				$this->validation->with_email = ($object['with_email'] == 't') ? 1 : 0;
				$this->validation->with_destination = ($object['with_destination'] == 't') ? 1 : 0;
			}
			else
			{				
				$rules = array('with_sms', 'with_email', 'with_destination');
				$this->validation->set_rules($this->contributor_model->getRules($rules));
	
				$this->validation->campaign_categories = $this->input->post('campaign_categories');
				
				if (!empty($this->validation->campaign_categories))
				{
					$arr = array();
					foreach($this->validation->campaign_categories as $id_category)
					{
						$arr[$id_category] = $this->data['all_categories'][$id_category];
					}	
					$this->validation->campaign_categories = $arr;
				}
				
				if ($this->validation->run() === TRUE)
				{
					$item['id'] 			= $this->validation->id;
					$item['with_sms'] 		= $this->validation->with_sms;
					$item['with_email'] 	= $this->validation->with_email;
					$item['fullname'] 		= $object['fullname'];
					$item['with_destination'] = $this->validation->with_destination;							
					
					$item['unwanted_categories'] = null;
					if (!empty($this->validation->campaign_categories))
					{
						$cats = implode(',', array_keys($this->validation->campaign_categories));
						$item['unwanted_categories'] = '{'.$cats.'}';
					}

					$this->contributor_model->update($item);
		          
					redirect($this->curl . '/index');
				}
			}	
		}
	
		$this->data['Title'] = 'РќР°СЃС‚СЂРѕРёС‚СЊ С‚Р°СЂРіРµС‚РёРЅРі';
		
		$this->renderLayout();
	}
	*/
	
	function stat($id = 0)
	{				
		if (!empty($id))
		{
			$object = $this->contributor_model->get($id);
			$this->data['Title'] = $this->name . ' / ' . T_('Р¤РёРЅР°РЅСЃС‹ Рё СЃС‚Р°С‚РёСЃС‚РёРєР°');					
		}
		
		$this->data['id']   	  = $id;
		$this->data['date_start'] = $this->input->post('date_start');
		$this->data['date_end']   = $this->input->post('date_end');
		
		$this->contributor_model->stat($id);
		
		$this->contributor_model->table_stat($id);
		
		$this->renderLayout();
	}
		
	function deleteItems()
	{		
		$data = $this->contributor_model->delete($_REQUEST['items']);

		echo $data;
	}

  function delete($id)
  {
    $data = $this->contributor_model->delete($id);

    redirect($this->curl . '/index');
  }
  
	function activity()
	{
		$data = $this->utils->publishItems($this->contributor_model->table, $this->contributor_model->prKey, $this->contributor_model->publishedField, $_REQUEST['items'], $_REQUEST['action']);
		echo $this->utils->php2js($data);
	}
		
  function __loginFree($login = null)
  { 
    return $this->contributor_model->loginFree($login);
  }

  function __phoneFree()
  {   
    if (!empty($this->data['ani']))
    {
        foreach ($this->data['ani'] as $phone)
        {
            $res = $this->contributor_model->phoneFree($phone);
            if (!$res)
            {
            	$this->validation->set_message('__phoneFree', 'Р’РІРµРґРµРЅРЅС‹Р№ <span class="black bold">«РќРѕРјРµСЂ С‚РµР»РµС„РѕРЅР°»</span> СѓР¶Рµ Р·Р°РЅСЏС‚ РІ Р±Р°Р·Рµ');            	
                return false;
            }
        }
        
        return true;
    }
    else
    {
        $this->validation->set_message('__phoneNumber', 'РќРµРѕР±С…РѕРґРёРјРѕ РґРѕР±Р°РІРёС‚СЊ <span class="black bold">«РќРѕРјРµСЂ С‚РµР»РµС„РѕРЅР°»</span>');
        return false;
    }
  }
    
  function __phoneValid()
  {   
    if (!empty($this->data['ani']))
    {
        foreach ($this->data['ani'] as $phone)
        {
            if (!preg_match( '/^[\-+]?[0-9]*\.?[0-9]+$/', $phone))
            {
            	echo $phone;
            	$this->validation->set_message('__phoneValid', 'РќРµРІРµСЂРЅС‹Р№ С„РѕСЂРјР°С‚ РїРѕР»СЏ <span class="black bold">«РќРѕРјРµСЂ С‚РµР»РµС„РѕРЅР°»</span>. Р”РѕРїСѓСЃС‚РёРјС‹Рµ СЃРёРјРІРѕР»С‹ - С‚РѕР»СЊРєРѕ С†РёС„СЂС‹.');
            }
        }
        
        return true;
    }
  }
  
	function details()
	{
		$id = $this->auth->getID();
		//does the object exist?
		if (!empty($id))
		{
			$object = $this->contributor_model->get($id);
			
			if (!count($object))
			{
				$this->renderElement('query_no_object');
				return false; 
			}
			
			if (!count($_POST))
			{
				//passing data
				$this->validation->user_ID 		= $object['user_ID'];
				$this->validation->user_login 	= $object['user_login']; 
				$this->validation->user_name 	= $object['user_name']; 
				$this->validation->user_email 	= $object['user_email'];
				$this->validation->user_phone 	= $object['user_phone'];
				$this->validation->user_password = $object['user_password'];							 
			}
			else
			{
				$rules = array('user_login', 'user_password', 'user_name', 'user_email', 'user_phone');
				$this->validation->set_rules($this->contributor_model->getRules($rules));
	
				if ($this->validation->run() === TRUE)
				{
					//prepare data
					$item['user_ID'] = $this->validation->user_ID;
					$item['user_login'] = $this->validation->user_login;
					$item['user_password'] = $this->validation->user_password;					
					$item['user_name'] = $this->validation->user_name;
					$item['user_email'] = $this->validation->user_email;
					$item['user_phone'] = $this->validation->user_phone;					
					
					$this->contributor_model->update($item);
					
					redirect($this->curl . '/index');
				}
			}	
		}
	
		$this->view 	= $this->curl . '/details';
		$this->renderLayout();
	}	
	
	function finance()
	{		
		$id = $this->auth->getID();
		
		if (!empty($id))
		{
			$object = $this->contributor_model->get($id);				
		}
		
		$this->contributor_model->stat($id);
		$this->contributor_model->table_stat($id);
		
		$this->data['Title'] = T_('Р В¤Р С‘Р Р…Р В°Р Р…РЎРѓРЎвЂ№ Р С‘ РЎРѓРЎвЂљР В°РЎвЂљР С‘РЎРѓРЎвЂљР С‘Р С”Р В°');	
		
		$this->renderLayout();
	}
}
?>